<template>
  <div>
    <div style="padding:10px">
      <el-input
        size="medium"
        v-model="searchData.account"
        placeholder="请输入账号"
        style="width: 180px"
      ></el-input>
      <el-input
        size="medium"
        v-model="searchData.name"
        placeholder="请输入姓名"
        style="width: 180px"
      ></el-input>
      <el-select v-model="searchData.sex" placeholder="请选择性别" clearable>
        <el-option label="男" :value="1"> </el-option>
        <el-option label="女" :value="2"> </el-option>
      </el-select>
      <el-button type="success" @click="searchBtn()">搜索</el-button>
      <el-button type="primary" @click="resetSearchBtn()">重置</el-button>
    </div>
    <div style="padding:10px">
      <el-button type="success" @click="adduserbtn()">添加</el-button>
      <el-button type="primary" @click="modifyuserbtn()">修改</el-button>
      <el-button type="danger" @click="deleteUser()">删除</el-button>
      <el-button type="info" @click="userRoleModifybtn()">角色分配</el-button>
    </div>
    <generaltable
      :headerData="headerData"
      :tableData="tableData"
      :total="total"
      :tableCellClick="tableCellClick"
      @SizeChange="SizeChange"
      @CurrentChange="CurrentChange"
    >
    </generaltable>
    <el-dialog
      :title="isadddialog ? '添加用户' : '修改用户'"
      :visible.sync="isdialog"
      :before-close="dialogClose"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="auto"
      >
        <el-row type="flex">
          <el-col :span="11">
            <el-form-item label="账号" prop="account">
              <el-input v-model="ruleForm.account"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="ruleForm.sex">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="密码" prop="password" v-if="isadddialog">
              <el-input v-model="ruleForm.password"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="phone">
              <el-input v-model="ruleForm.phone"></el-input>
            </el-form-item>
            <el-form-item label="是否启用" prop="status">
              <el-switch
                v-model="ruleForm.status"
                :active-value="1"
                :inactive-value="2"
              ></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="2"></el-col>
          <el-col :span="11">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="ruleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="ruleForm.email"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="isPassword" v-if="isadddialog">
              <el-input v-model="ruleForm.isPassword"></el-input>
            </el-form-item>
            <el-form-item label="所属部门" prop="deptName">
              <el-popover v-model="visible">
                <el-select
                  slot="reference"
                  v-model="ruleForm.deptName"
                  placeholder="请选择活动区域"
                >
                </el-select>
                <el-tree
                  :data="deptListData"
                  :props="defaultProps"
                  @node-click="treeChenkDept"
                ></el-tree>
              </el-popover>
            </el-form-item>
            <el-form-item label="出生日期" prop="birthday">
              <el-date-picker
                v-model="ruleForm.birthday"
                type="date"
                placeholder="选择出生日期时间"
                value-format="yyyy-MM-dd HH-mm-ss"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button
            type="primary"
            @click="isadddialog ? addUser() : modifyUser()"
            >提交</el-button
          >
          <el-button @click="undo()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      title="角色分配"
      :visible.sync="isdialogA"
      :before-close="dialogCloseRole"
    >
      <template>
        <el-checkbox-group v-model="checkedIds">
          <el-checkbox
            v-for="item of roleList"
            :label="item.id"
            :key="item.id"
            >{{ item.name }}</el-checkbox
          >
        </el-checkbox-group>
        <el-button type="primary" @click="rolemodify">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import generaltable from "@/components/generaltable.vue";
import {
  userTableData,
  userDelete,
  deptList,
  userAdd,
  userModify,
  userRoleList,
  userRoleModify,
  userSearch
} from "@/api/userManagement.js";
export default {
  name: "UserManagement",
  data() {
    var checkPasword = (rule, value, callback) => {
      let _self = this;
      if (value != _self.ruleForm.password) {
        callback(new Error("两次输入密码不一致"));
      } else {
        callback();
      }
    };
    return {
      isdialogA: false,
      searchData: { account: "", name: "", sex: "" },
      total: 0,
      page: 1,
      checkedIds: [],
      limit: 20,
      roleList: [],
      isdialog: false,
      isadddialog: false,
      visible: false,
      headerData: [
        {
          prop: "account",
          label: "账号"
        },
        {
          prop: "name",
          label: "姓名"
        },
        {
          prop: "sexName",
          label: "性别"
        },
        {
          prop: "roleName",
          label: "角色"
        },
        {
          prop: "deptName",
          label: "部门"
        },
        {
          prop: "email",
          label: "邮箱"
        },
        {
          prop: "phone",
          label: "电话"
        },
        {
          prop: "createTime",
          label: "创建时间"
        },
        {
          prop: "statusName",
          label: "状态"
        }
      ],
      tableData: [],
      deptListData: [],
      currentrow: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      ruleForm: {
        account: "",
        sex: 1,
        password: "",
        phone: "",
        status: 1,
        name: "",
        email: "",
        isPassword: "",
        deptName: "",
        deptid: "",
        birthday: ""
      },
      rules: {
        account: [
          { required: true, message: "请输入账号", trigger: "blur" },
          { min: 3, max: 20, message: "长度在3-20字符", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { length: 11, message: "格式不正确", trigger: "blur" }
        ],
        name: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          { min: 2, max: 20, message: "长度在2-20字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        isPassword: [
          { required: true, message: "请确认密码", trigger: "blur" },
          { validator: checkPasword, trigger: "blur" }
        ],
        deptName: [
          { required: true, message: "请选择所在部门", trigger: "change" }
        ]
      }
    };
  },
  mounted() {
    let _self = this;
    _self.obtainUserTable();
  },
  methods: {
    tableCellClick(row) {
      let _self = this;
      _self.currentrow = row;
    },
    treeChenkDept(val) {
      let _self = this;
      _self.ruleForm.deptName = val.label;
      _self.ruleForm.deptid = val.id;
    },
    adduserbtn() {
      let _self = this;
      _self.isdialog = true;
      _self.isadddialog = true;
      _self.obtaindeptList();
    },
    userRoleModifybtn() {
      let _self = this;
      if (Object.keys(_self.currentrow).length !== 0) {
        _self.isdialogA = true;
        let data = {
          idUSer: _self.currentrow.id
        };
        userRoleList(data).then(res => {
          if (res.code == 20000) {
            _self.roleList = [];
            for (let item of res.data.treeData) {
              if (item.name.length !== 0) {
                _self.roleList.push({
                  id: item.id,
                  name: item.name
                });
              }
            }
            _self.checkedIds = res.data.checkedIds;
          }
        });
      } else {
        _self.$message({
          message: "请选择操作项！",
          type: "warning"
        });
      }
    },
    modifyuserbtn() {
      let _self = this;
      console.log(_self.currentrow);
      _self.obtaindeptList();
      let currentrow = JSON.parse(JSON.stringify(_self.currentrow));
      if (Object.keys(_self.currentrow).length !== 0) {
        _self.isdialog = true;
        _self.isadddialog = false;
        _self.$nextTick(() => {
          _self.ruleForm.id = _self.currentrow.id;
          _self.ruleForm.account = _self.currentrow.account;
          _self.ruleForm.sex = _self.currentrow.sex;
          _self.ruleForm.phone = _self.currentrow.phone;
          _self.ruleForm.status = _self.currentrow.status;
          _self.ruleForm.name = _self.currentrow.name;
          _self.ruleForm.email = _self.currentrow.email;
          _self.ruleForm.deptName = _self.currentrow.deptName;
          _self.ruleForm.deptid = _self.currentrow.deptid;
          _self.ruleForm.birthday = _self.currentrow.birthday
            .split(":")
            .join("-");
        });
      } else {
        _self.$message({
          message: "请选择操作项！",
          type: "warning"
        });
      }
    },
    undo() {
      let _self = this;
      _self
        .$confirm("确认取消当前操作？", "提示", { type: "warning" })
        .then(() => {
          _self.isdialog = false;
        })
        .catch();
    },
    dialogClose() {
      let _self = this;
      _self
        .$confirm("确认取消当前操作？", "提示", { type: "warning" })
        .then(() => {
          _self.$refs.ruleForm.resetFields();
          _self.isdialog = false;
          _self.$message({
            type: "info",
            message: "已取消当前操作"
          });
        })
        .catch(() => {});
    },
    dialogCloseRole() {
      let _self = this;
      _self
        .$confirm("确认取消分配操作?", "提示", { type: "warning" })
        .then(() => {
          _self.isdialogA = false;
        })
        .catch(() => {});
    },
    CurrentChange(val) {
      let _self = this;
      _self.page = val;
      _self.obtainUserTable();
    },
    SizeChange(val) {
      let _self = this;
      _self.limit = val;
      _self.obtainUserTable();
    },
    obtainUserTable() {
      let _self = this;
      let data = {
        page: _self.page,
        limit: _self.limit
      };
      userTableData(data).then(res => {
        _self.tableData = [];
        for (let item of res.data.records) {
          _self.tableData.push(item);
        }
        _self.total = res.data.total;
      });
    },
    obtaindeptList() {
      let _self = this;
      deptList().then(res => {
        if (res.code == 20000) {
          _self.deptListData = res.data;
        }
      });
    },
    addUser() {
      let _self = this;
      console.log(_self.ruleForm.birthday, typeof _self.ruleForm.birthday);
      _self.$refs.ruleForm.validate(valid => {
        if (valid) {
          let data = {
            id: "",
            account: _self.ruleForm.account,
            name: _self.ruleForm.name,
            birthday: _self.ruleForm.birthday,
            sex: _self.ruleForm.sex,
            email: _self.ruleForm.email,
            dept: "",
            status: _self.ruleForm.status,
            deptid: _self.ruleForm.deptid,
            deptName: _self.ruleForm.deptName,
            phone: _self.ruleForm.phone,
            createtime: "0-0-0 0:0:0"
          };
          userAdd(data).then(res => {
            if (res.code == 20000) {
              _self.isdialog = false;
              _self.obtainUserTable();
            }
          });
        }
      });
    },
    modifyUser() {
      let _self = this;
      _self.$refs.ruleForm.validate(valid => {
        if (valid) {
          let data = {
            birthday: _self.ruleForm.birthday,
            modifyBy: 1,
            deptName: _self.ruleForm.deptName,
            salt: _self.currentrow.salt,
            roleid: _self.currentrow.roleid,
            sex: _self.ruleForm.sex,
            deptid: _self.ruleForm.deptid,
            password: "",
            modifyTime: "2022-10-17 10:55:14",
            createTime: _self.currentrow.createTime,
            phone: _self.ruleForm.phone,
            sexName: _self.currentrow.sexName,
            name: _self.ruleForm.name,
            roleName: _self.currentrow.roleName,
            statusName: _self.currentrow.statusName,
            id: _self.currentrow.id,
            account: _self.ruleForm.account,
            email: _self.ruleForm.email,
            status: _self.ruleForm.status,
            createtime: "0-0-0 0:0:0"
          };
          userModify(data).then(res => {
            if (res.code == 20000) {
              _self.isdialog = false;
              _self.$message({
                type: "success",
                message: "提交成功"
              });
              _self.obtainUserTable();
            }
          });
        }
      });
    },
    deleteUser() {
      let _self = this;
      if (
        _self.currentrow.id.length != 0 &&
        _self.currentrow.id != 1 &&
        _self.currentrow.id != 2 &&
        _self.currentrow.statusName != "被删除"
      ) {
        _self
          .$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(async () => {
            let data = {
              userId: _self.currentrow.id
            };
            userDelete(data).then(res => {
              if ((res.code = 20000)) {
                _self.$message({
                  type: "success",
                  message: "删除成功!"
                });
              }
            });
            _self.obtainUserTable();
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      } else {
        if (_self.currentrow.id.length == 0) {
          _self.$message({
            type: "warning",
            message: "请选择操作项"
          });
        } else if (_self.currentrow.statusName == "被删除") {
          _self.$message({
            type: "warning",
            message: "该用户已删除"
          });
        } else {
          _self.$message({
            type: "error",
            message: "该用户为系统默认用户，无法删除"
          });
        }
      }
    },
    rolemodify() {
      let _self = this;
      let data = {
        userId: _self.currentrow.id,
        roleIds: _self.checkedIds.join(",")
      };
      userRoleModify(data)
        .then(res => {
          if (res.code == 20000) {
            _self.isdialogA = false;
            _self.obtainUserTable();
            _self.$message({
              type: "success",
              message: "角色分配成功"
            });
          }
        })
        .catch(res => {
          _self.$message({
            type: "warning",
            message: "请选择用户身份"
          });
        });
    },
    searchBtn() {
      let _self = this;
      let data = {
        page: _self.page,
        limit: _self.limit,
        account: _self.searchData.account,
        name: _self.searchData.name,
        sex: _self.searchData.sex
      };
      userSearch(data).then(res => {
        console.log(res);
        if (res.code == 20000) {
          _self.tableData = [];
          for (let item of res.data.records) {
            _self.tableData.push(item);
          }
        }
      });
    },
    resetSearchBtn() {
      let _self = this;
      _self.searchData.account = "";
      _self.searchData.name = "";
      _self.searchData.sex = "";
      _self.searchBtn();
    }
  },
  components: {
    generaltable
  }
};
</script>
<style></style>
